package com.jumi.microservice.service.logistics.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.jumi.microservice.dto.logistics.MergeListRequest;
import com.jumi.microservice.dto.logistics.excel.ExcelSpiltMerge;
import com.jumi.microservice.service.logistics.admin.MergeService;

import java.util.ArrayList;
import java.util.List;

/**
 * @author by mazhao
 * @Classname SelfWaitSendListener
 * @Description TODO
 * @Date 2020/9/9 13:47
 */
public class SpiltMergeListener extends AnalysisEventListener<ExcelSpiltMerge> {

    private MergeService mergeService;

    private MergeListRequest mergeListRequest;

    List<ExcelSpiltMerge> list = new ArrayList<>();

//    private static final int BATCH_COUNT = 1000000;

    @Override
    public void invoke(ExcelSpiltMerge excelSpiltMerge, AnalysisContext analysisContext) {
        list.add(excelSpiltMerge);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
//        if (list.size() >= BATCH_COUNT) {
//            saveData(list);
//            // 存储完成清理 list
//            list.clear();
//        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //全部读完业务逻辑
        saveData(list,mergeListRequest);
    }

    public SpiltMergeListener(MergeService mergeService, MergeListRequest mergeListRequest) {
        this.mergeService = mergeService;
        this.mergeListRequest = mergeListRequest;
    }

    public void saveData(List<ExcelSpiltMerge> list,MergeListRequest mergeListRequest){
        mergeService.excelImportHandler(list,mergeListRequest);
    }
}
